// Boot loader.
//
// Part of the boot block, along with bootasm.S, which calls bootmain().
// bootasm.S has put the processor into protected 32-bit mode.
// bootmain() loads an ELF kernel image from the disk starting at
// sector 1 and then jumps to the kernel entry routine.

#include "types.h"
#include "elf.h"
#include "x86.h"
#include "memlayout.h"

#define SECTSIZE  512

void readseg(uchar*, uint, uint);

// 整个c文件只有bootmain是用于被bootasm.S调用的
void
bootmain(void)
{
  struct elfhdr *elf;
  struct proghdr *ph, *eph;
  void (*entry)(void);
  uchar* pa;

  // 强制类型转换操作声明了这个地址是一个“struct elfhdr”类型空间的起始地址，但还没申请内存空间
  elf = (struct elfhdr*)0x10000;  // scratch space   这个物理地址存放的是内核文件的ELF头，加载ELF头后根据里面的信息继续加载内核主体程序到0x100000，注意一条4个0一条5个0

  // Read 1st page off disk
  // exec使用readi函数和用namei(path)读到的inode来加载elf文件，而这里是直接读了0～4096的段直接装进指定物理地址，并直接认为这一段就是个elf文件
  readseg((uchar*)elf, 4096, 0);  //从虚拟地址0处（内核）读取4096个字节 装载进物理地址elf即0x10000处

  // Is this an ELF executable?
  if(elf->magic != ELF_MAGIC)  // 通过 ELF 头检查这是否等于ELF_MAGIC来确定是否真的是一个 ELF 文件
    return;  // let bootasm.S handle error   报错，返回bootasm.S中

  // Load each program segment (ignores ph flags).
  ph = (struct proghdr*)((uchar*)elf + elf->phoff); //获得程序段头文件（结构体）的首地址
  //从磁盘中 ELF 头之后 `off` 字节处读取扇区的内容，并写到内存中地址 `paddr` 处
  eph = ph + elf->phnum;// end of ph
  for(; ph < eph; ph++){  
    pa = (uchar*)ph->paddr;   // 这个paddr是怎么提前有值的？
    readseg(pa, ph->filesz, ph->off);
    if(ph->memsz > ph->filesz)
      stosb(pa + ph->filesz, 0, ph->memsz - ph->filesz);  //调用 `stosb` 将段的剩余部分置零。`stosb`使用 x86 指令 `rep stosb` 来初始化内存块中的每个字节
  }

  // Call the entry point from the ELF header.
  // Does not return!
  entry = (void(*)(void))(elf->entry);    //内核第一条指令的执行地址。在 xv6 中入口指令的地址是 0x10000c
  entry();  //执行entry，跳转到entry.S，此处加载的文件就是entry.S，elf->entry的地质就是entry.S程序第一条指令的地址
}

void
waitdisk(void)
{
  // Wait for disk ready.
  while((inb(0x1F7) & 0xC0) != 0x40)
    ;
}

// Read a single sector at offset into dst.
void
readsect(void *dst, uint offset)
{
  // Issue command.
  waitdisk();
  outb(0x1F2, 1);   // count = 1
  outb(0x1F3, offset);
  outb(0x1F4, offset >> 8);
  outb(0x1F5, offset >> 16);
  outb(0x1F6, (offset >> 24) | 0xE0);
  outb(0x1F7, 0x20);  // cmd 0x20 - read sectors

  // Read data.
  waitdisk();
  insl(0x1F0, dst, SECTSIZE/4);
}

// Read 'count' bytes at 'offset' from kernel into physical address 'pa'.
// Might copy more than asked.
void
readseg(uchar* pa, uint count, uint offset)
{
  uchar* epa;  // end of pa

  epa = pa + count;  //用作for循环结束边界

  // Round down to sector boundary.
  pa -= offset % SECTSIZE;  //求余操作，

  // Translate from bytes to sectors; kernel starts at sector 1.
  offset = (offset / SECTSIZE) + 1;

  // If this is too slow, we could read lots of sectors at a time.
  // We'd write more to memory than asked, but it doesn't matter --
  // we load in increasing order.
  for(; pa < epa; pa += SECTSIZE, offset++)
    readsect(pa, offset);
}
